<?php

namespace Classes;

use Classes\db\DBConnection;
use PDO;

class Relation {
	public static function insertRelation($following_id, $followed_id) {
		$connection = DBConnection::getDBConnection ();
		
		$statement = "INSERT INTO `relation`(`following_user`, `followed_user`)
					 		VALUES(:FOLLOWING_ID, :FOLLOWED_ID)";
		
		$stmt = $connection->prepare ( $statement );
		$stmt->bindValue ( ":FOLLOWING_ID", $following_id, PDO::PARAM_INT );
		$stmt->bindValue ( ":FOLLOWED_ID", $followed_id, PDO::PARAM_INT );
		$stmt->execute ();
	}
	public static function deleteRelation($following_id, $followed_id) {
		$connection = DBConnection::getDBConnection ();
		
		$statement = "DELETE FROM `relation`
							WHERE `following_user`=:FOLLOWER_ID and `followed_user`=:FOLLOWED_ID";
		
		$stmt = $connection->prepare ( $statement );
		$stmt->bindValue ( ":FOLLOWER_ID", $following_id, PDO::PARAM_INT );
		$stmt->bindValue ( ":FOLLOWED_ID", $followed_id, PDO::PARAM_INT );
		$stmt->execute ();
	}
	public static function getFollowings($following_id) {
		$connection = DBConnection::getDBConnection ();
		
		$statement = "SELECT user.user_name, user.user_id 
							FROM `user`
							INNER JOIN relation
							WHERE relation.followed_user=user.user_id and relation.following_user=:FOLLOWER_ID";
		
		$stmt = $connection->prepare ( $statement );
		$stmt->bindValue ( ":FOLLOWER_ID", $following_id, PDO::PARAM_INT );
		$stmt->execute ();
		return $stmt->fetchAll ();
	}
	public static function getFollowers($followed_id) {
		$connection = DBConnection::getDBConnection ();
		
		$statement = "SELECT user.user_name, user.user_id
							FROM `user`
							INNER JOIN relation
							WHERE relation.following_user=user.user_id and relation.followed_user=:FOLLOWED_ID";
		
		$stmt = $connection->prepare ( $statement );
		$stmt->bindValue ( ":FOLLOWED_ID", $followed_id, PDO::PARAM_INT );
		$stmt->execute ();
		return $stmt->fetchAll ();
	}
	public static function isRelation($following_id, $followed_id) {
		$connection = DBConnection::getDBConnection ();
		
		$statement = "SELECT *
						FROM `relation`
						WHERE `following_user`=:FOLLOWER_ID and `followed_user`=:FOLLOWED_ID";
		
		$stmt = $connection->prepare ( $statement );
		
		$stmt->bindValue ( ":FOLLOWER_ID", $following_id, PDO::PARAM_INT );
		$stmt->bindValue ( ":FOLLOWED_ID", $followed_id, PDO::PARAM_INT );
		
		$stmt->execute ();
		$result = $stmt->fetchAll ();
		return $stmt->rowCount ();
	}
	
}